package com.dondedesigns.eh.controller.index;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.dondedesigns.eh.persistence.ApprovedStatus;
import com.dondedesigns.eh.persistence.User;
import com.dondedesigns.eh.persistence.dao.UserDAO;
import com.dondedesigns.eh.util.EHConstants;
import com.dondedesigns.eh.util.MessageConstants;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

public class Login extends ActionSupport implements SessionAware, ModelDriven<User>{
	private User user = new User();
	
	private UserDAO userDAO;
	
	@SuppressWarnings("unchecked")
	private Map session;
	
	@SuppressWarnings("unchecked")
	@Override
	@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName="username", message=MessageConstants.USERNAME_REQUIRED)
	public String execute () {
		if (authenticate()) {
			session.put(EHConstants.USER, user);
			return SUCCESS;
		}
		return INPUT;
	}

	@Override
	public User getModel() {
		return user;
	}
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setSession(Map session) {
		this.session = session;
	}
	
	public boolean authenticate () {
		User tempUser = null;
		tempUser = userDAO.getUser(user.getUsername(), user.getPassword());
		if (tempUser != null && tempUser.getApprovedStatus().equals(ApprovedStatus.APPROVED)) {
			user = tempUser;
			return true;
		}
		if (tempUser == null) {
			addActionError(MessageConstants.LOGIN_ERROR);
		} else if (!tempUser.getApprovedStatus().equals(ApprovedStatus.APPROVED)) {
			addActionError(MessageConstants.LOGIN_NOT_AUTHORIZED);
		}
		return false;
		
	}

}
